/**
 * OSAmI: Open Source Ambient Intelligence
 * Copyright (C) 2010 Thales Communications, SA
 * Contact: osami-general@osami-commons.org
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307
 * USA
 */
package org.osami.commons.encryption.test;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;

import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;

/**
 * This class is used to generate keys
 * @author Marcel Arrufat Arias
 *
 */
public class KeyGeneratorMain {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        try {
            String algorithm = "Rijndael";

            String keyName = "key_" + algorithm + ".ks";
            int keySize = 128; // 128, 192 or 256 bits

            keyName = "./src/test/resources/" + keyName;
            System.out.println("Generating key for algorithm " + algorithm + " with " + keySize + " bits of keysize");

            KeyGenerator instance = KeyGenerator.getInstance(algorithm);
            instance.init(keySize);
            SecretKey key = instance.generateKey();

            storeKey(key.getEncoded(), keyName);
            System.out.println("Key stored succesfully");

        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    private static void storeKey(byte[] encoded, String keyName) throws IOException {

        FileOutputStream fos = new FileOutputStream(keyName);
        fos.write(encoded);
        fos.flush();
        fos.close();

    }

}
